package com.wuzf.mall.net

import android.content.Context
import android.os.Handler
import com.wuzf.mall.global.GlobalKeys
import com.wuzf.mall.global.Mall
import com.wuzf.mall.loading.LoadStyles
import com.wuzf.mall.loading.MallLoader
import com.wuzf.mall.net.callback.*
import retrofit2.Call
import java.util.*

// 建造者模式
class RestClient private constructor(
    private var url: String?,
    private var params: WeakHashMap<String, Any>?,
    private var success: ISuccess?,
    private var failure: IFailure?,
    private var error: IError?,
    private var complete: IComplete?,
    private var context: Context? = null,
    private var styles: LoadStyles? = null,
) {

    companion object {
        fun builder(): RestClientBuilder = RestClientBuilder()
    }

    private fun request(method: HttpMethod) {
        if (styles != null) {
            MallLoader.createLoader(context, styles)
        }
        val result: Call<String> = when (method) {
            HttpMethod.GET -> RestCreator.restService.get(url ?: "", params)
            HttpMethod.POST -> RestCreator.restService.post(url ?: "", params)
            else -> throw RuntimeException("method type is error")
        }
        result.enqueue(RequestCallbacks(success, failure, error, complete))
    }

    fun get() {
        request(HttpMethod.GET)
    }

    fun post() {
        request(HttpMethod.POST)
    }


    class RestClientBuilder(
        private var url: String? = null,
        private var success: ISuccess? = null,
        private var failure: IFailure? = null,
        private var error: IError? = null,
        private var complete: IComplete? = null,
        private var context: Context? = null,
        private var styles: LoadStyles? = null,
    ) {

        private val params = WeakHashMap<String, Any>()

        fun url(url: String): RestClientBuilder {
            this.url = url
            return this
        }

        fun params(key: String, value: String): RestClientBuilder {
            params[key] = value
            return this
        }

        fun success(callback: ISuccess): RestClientBuilder {
            this.success = callback
            return this
        }

        fun failure(callback: IFailure): RestClientBuilder {
            this.failure = callback
            return this
        }

        fun error(callback: IError): RestClientBuilder {
            this.error = callback
            return this
        }

        fun complete(callback: IComplete): RestClientBuilder {
            this.complete = callback
            return this
        }

        fun loader(
            context: Context?,
            loadStyles: LoadStyles = LoadStyles.BallSpinFadeLoaderIndicator
        ): RestClientBuilder {
            this.context = context
            this.styles = loadStyles
            return this
        }

        fun build(): RestClient {
            return RestClient(url, params, success, failure, error, complete, context, styles)
        }
    }
}